package com.platform.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

public class HeaderDealFilter extends OncePerRequestFilter{
	
	private String staticUrl;
	
    @Override
    public void initFilterBean() throws ServletException {
    	staticUrl = this.getFilterConfig().getInitParameter("staticUrl");
    }

	@Override
	protected void doFilterInternal(
			HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
    	String[] whiteList = staticUrl.split(",");
    	String myOrigin = request.getHeader("origin");
    	boolean isValid = false;
    	for( String ip : whiteList ) {
    		if( myOrigin != null && myOrigin.equals(ip) ){
    			isValid = true;
    			break;
    		}
    	}

    	if(isValid) {
            //支持跨域请求
    		response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization,Content-Type,X-Nideshop-Token");

            response.setHeader("Access-Control-Allow-Credentials", "true");
    	}
//    	if (request.getMethod().equals("OPTIONS")) {
//            return;
//        }
//		response.setHeader("Access-Control-Allow-Origin", staticUrl); 
		filterChain.doFilter(request, response);
	}

}
